import { Node, Shape, Cell } from "@antv/x6";
import { nextId } from '../utils';
import { defaultPortGroup } from './_default';
import lodash from 'lodash';
import GatewayExclusiveIcon from '../icons/GatewayExclusive.svg';
import GatewayInclusiveIcon from '../icons/GatewayInclusive.svg';
import GatewayParallelIcon from '../icons/GatewayParallel.svg';

const iconMap:any = {
  exclusiveGateway: GatewayExclusiveIcon,
  parallelGateway: GatewayParallelIcon,
  inclusiveGateway: GatewayInclusiveIcon
}

export default class GatewayNode extends Shape.Polygon{
  private static default:Node.Metadata = {
    width: 60,
    height: 60,
    markup: [
      { tagName: 'polygon', selector: 'body' },
      { tagName: 'image', selector: 'img' },
      { tagName: 'text', selector: 'label' },
    ],
    attrs: {
      body: {
        refPoints: '0,10 10,0 20,10 10,20',
        strokeWidth: 10,
        stroke: '#EFD0FF',
        fill: '#EFD0FF',
        strokeLinejoin: "round"
      },
      img: {
        x: 15,
        y: 15,
        width: 30,
        height: 30,
        'xlink:href': GatewayExclusiveIcon
      },
      label: {
        fontSize: 12,
        fill: '#262626',
      },
    },
    ports: {
      groups: {
        top: { ...defaultPortGroup, position: "top" },
        right: { ...defaultPortGroup, position: "right" },
        bottom: { ...defaultPortGroup, position: "bottom" },
        left: { ...defaultPortGroup, position: "left" }
      },
      items: [
        { id: "P0_0", group: "top" },
        { id: "P1_0", group: "right" },
        { id: "P2_0", group: "bottom" },
        { id: "P3_0", group: "left" },
      ],
    },
    data: {
      tag: 'exclusiveGateway'
    }
  }
  private static complement = (metadata: Node.Metadata={}):Node.Metadata=>{
    const adds = {} as Node.Metadata;
    adds.id = metadata.id || nextId();
    adds.attrs = {img:{'xlink:href': iconMap[metadata.data?.tag] || GatewayExclusiveIcon}};
    return lodash.mergeWith({},GatewayNode.default,metadata,adds);
  }

  constructor(metadata: Node.Metadata={}){
    super(GatewayNode.complement(metadata));
  }

  updateData(data: any, options?: Cell.SetOptions): this {
    const icon = iconMap[(data as any).tag] || GatewayExclusiveIcon;
    this.setAttrs({img:{"xlink:href":icon}});
    // 更新属性ports会消失，瞬间添加删除port来刷新渲染
    this.addPort({id:'X'});
    this.removePort('X');
    return super.updateData(data, options);
  }
}
